package com.chongzi.cloud;

public class code25 {
    public ListNode reverseKGroup(ListNode head, int k) {
            int n=0;
            for (ListNode cur=head;cur!=null;cur=cur.next){
                n++;
            }
            ListNode dummy=new ListNode(0,head);
            ListNode pre=dummy;
            ListNode end=dummy;
            while (end.next!=null){
                for (int i=0;i<k&&end!=null;i++){
                    end=end.next;
                }
                if (end==null){
                    break;
                }
                ListNode temp=end.next;

                end.next=null;
                ListNode start=pre.next;
                pre.next=null;
                pre.next=reverse(start);
                start.next=temp;
                pre=start;
                end=start;


            }
            return dummy.next;
    }
    private ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }


}
